package org.agridata.akvisualization.controller.redis;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private  RedisTemplate redisTemplate;
//    private final StringRedisTemplate stringRedisTemplate;
//    private final RedisTemplate<String, String> redisTemplate;
////
//    public RedisController(RedisTemplate<String, String> redisTemplate, StringRedisTemplate stringRedisTemplate) {
//        this.redisTemplate = redisTemplate;
//        this.stringRedisTemplate = stringRedisTemplate;
//    }

    // 添加用户到Redis
    @PostMapping("/addUser")
    public String addUser(@RequestBody JSONObject user) {
        redisTemplate.opsForValue().set(user.get("id").toString(), user.toJSONString());
        return "User added successfully!";
    }

    // 根据ID从Redis获取用户
    @GetMapping("/getUser/{id}")
    public Object getUser(@PathVariable String id) {
        return redisTemplate.opsForValue().get(id);
    }

    // 根据ID从Redis删除用户
    @DeleteMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable String id) {
        redisTemplate.delete("getAnimalRatioKey1");
        redisTemplate.delete("getAnimalRatioKey2");
        redisTemplate.delete("getOriginStatisticsKey");
        return "User deleted successfully!";
    }
    // 编辑键的值
    @PutMapping("/editValue/{key}")
    public String editValue(@PathVariable String key, @RequestBody String newValue) {
        if (redisTemplate.hasKey(key)) {
            redisTemplate.opsForValue().set(key, newValue);
            return "Value for key '" + key + "' updated successfully!";
        } else {
            return "Key '" + key + "' does not exist!";
        }
    }

//    // 获取所有key（分页）
//    @GetMapping("/getAllKeys")
//    public Set<String> getAllKeys(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int pageSize) {
//        Set<String> allKeys = stringRedisTemplate.keys("*");
//        int fromIndex = page * pageSize;
//        int toIndex = Math.min(fromIndex + pageSize, allKeys.size());
//        return allKeys.stream().skip(fromIndex).limit(toIndex - fromIndex).collect(Collectors.toSet());
//    }

}
